/*
 * @Author: zhangxiao
 * @Email: zhangxiao0125@163.com
 * @Date: 2020-05-26 16:11:58
 * @Last Modified by: zhangxiao
 * @Last Modified time: 2020-07-02 15:06:34
 * @Description: 拍照
 */

import 'dart:async';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_code_framework/model_data/events/base_event.dart';
import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';

import 'package:path_provider/path_provider.dart';
import 'package:screen/screen.dart';

class PicCamera extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _PicCameraState();
  }
}

void logError(String code, String message) =>
    print('Error: $code\nError Message: $message');

class _PicCameraState extends State<PicCamera> with WidgetsBindingObserver {
  CameraController cameraController;
  bool _startVisibility=true; //开始按钮
  bool _isFrontCamera=false;  //是否前置摄像头
  String _photoPath='';       //拍摄图像地址
 
  String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initCamera();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
    cameraController.dispose();
  }
 
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (cameraController == null || !cameraController.value.isInitialized) {
      return;
    }
    if (state == AppLifecycleState.inactive) {
      cameraController?.dispose();
    } else if (state == AppLifecycleState.resumed) {
      if (cameraController != null) {
        onNewCameraSelected(cameraController.description);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
     body: Column(
      children: <Widget>[
        Expanded(
              child: Stack(
                children: <Widget>[
                //摄像头区域
                _cameraPreviewWidget(),
                  //头部导航
                _topBarWidget(),
                //拍照
                _startShotWidget(),                
           
              ],
            ),
            flex: 1),
      ],
    ) ,
   );
  }

  // 预览相机显示区域
  Widget _cameraPreviewWidget() {
    if (cameraController == null || !cameraController.value.isInitialized) {
      return const Text(
        '',
        style: TextStyle(
          color: Colors.white,
          fontSize: 24.0,
          fontWeight: FontWeight.w900,
        ),
      );
    } else {
     final size= MediaQuery.of(context).size;
    return ClipRect(
        child: Container(
          child: Transform.scale(
            scale: cameraController.value.aspectRatio / size.aspectRatio,
            child: Center(
              child: AspectRatio(
                aspectRatio: cameraController.value.aspectRatio,
                child:_photoPath!='' && !_startVisibility?Image.file(File(_photoPath)): CameraPreview(cameraController),
              ),
            ),
          ),
        ),
      );
    }
  }
  
///////////////////////////////////////////////////////////////////////////////////////////////////
  //底部区域
  Widget _buttomBaseWidget(List<Widget> _widget){
      return Positioned(
              bottom: 0.0,
                child: Container(
                        width:MediaQuery.of(context).size.width,
                        height: 64.0,
                        color: Color.fromRGBO(216, 216, 216, 0.5),
                          child:Stack(
                            alignment: Alignment.center,
                            children:_widget
                          ),
                )
             );
  }

 
 //appbar 按钮 
  Widget _topBarWidget(){
     return Container(
          width:MediaQuery.of(context).size.width,
          height: (MediaQuery.of(context).padding.top*2),
          color: Color.fromRGBO(216, 216, 216, 0.5),
              child:Stack(
                children: <Widget>[
                  Positioned(
                    left: 20.0,
                    top: 43,
                    child: GestureDetector(
                      child:Icon(SFSymbols.chevron_left),
                      onTap: (){
                        //删除临时文件并返回上级页面
                         Directory(_photoPath).delete(recursive: true).then((FileSystemEntity fileSystemEntity) {});
                         Navigator.of(context).pop();
                      },
                    )
                  ),
                  Visibility(
                    visible:!_startVisibility ,
                    child:Positioned(
                    right: 20.0,
                    top: 43,
                    child:SizedBox(
                      height:26.0,
                      width: 60.0,
                      child:RaisedButton(
                        shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.all(Radius.circular(6.0))
                               ),
                        color: Color.fromARGB(255, 236,115, 100),
                        child: Text('完 成',style: TextStyle(fontSize:12,color: Theme.of(context).primaryTextTheme.button.color),),onPressed: (){
                              G.eventBus.fire(RecordingPothoPathEvent(_photoPath));//发送订阅消息 照片存储路径
                              Navigator.of(context).pop();
                        }) ,
                    ) 
                  ) ,
                  )
                ]
              ),
            );
  }

  //拍照/前置按钮
  Widget _startShotWidget(){
   return  Visibility(
      visible: _startVisibility,
      child: _buttomBaseWidget([
      GestureDetector(
            child:Container(
              height: 50,
              width: 50,
              decoration: new BoxDecoration(
                color: Colors.transparent,
                borderRadius: BorderRadius.all(Radius.circular(150.0)),
                border: new Border.all(width: 4, color: Colors.white),
              ),
              child: Container(
                      decoration: new BoxDecoration(
                          color: Colors.red,
                        borderRadius: BorderRadius.all(Radius.circular(150.0)),
                        border: new Border.all(width: 2, color: Color.fromARGB(255, 236,115, 100)),
                      ),child: Text(''),
              )
            ),
            onTap:cameraController != null && cameraController.value.isInitialized && !cameraController.value.isRecordingVideo? onVideoRecordButtonPressed: null
          ),
        
         Positioned(
          right: 20.0,
          child:GestureDetector(
            child: Container(
               child: Icon(SFSymbols.camera_rotate),
           ),
           onTap:(){
             !_isFrontCamera?_initCamera(1):_initCamera();
             setState(() {
               _isFrontCamera= !_isFrontCamera;
             });
           },
          )
         )
   ]));
  }
 
  //设置屏幕常亮
 _initPlatformState() async {
    double brightness = await Screen.brightness;
    setState((){
       Screen.setBrightness(brightness);
        Screen.keepOn(true);
    });
  }
  

  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  void onNewCameraSelected(CameraDescription cameraDescription) async {
    if (cameraController != null) {
      await cameraController.dispose();
    }
    cameraController = CameraController(
      cameraDescription,
      ResolutionPreset.medium
    );

    // If the cameraController is updated then update the UI.
    cameraController.addListener(() {
      if (mounted) setState(() {});
      if (cameraController.value.hasError) {
      }
    });

    try {
      await cameraController.initialize();
    } on CameraException catch (e) {
   
    }
    if (mounted) {
      setState(() {});
    }
  }
  
  void onVideoRecordButtonPressed() {
    print(cameraController.value.isRecordingVideo);
    startVideoRecording().then((String filePath) {
      _startVisibility=false;
      setState(() {});
    });
  }

  Future<String> startVideoRecording() async {
    if (!cameraController.value.isInitialized) {
      return null;
    }
    final Directory extDir = await getApplicationDocumentsDirectory();
    final String dirPath = '${extDir.path}/Movies/flutter_test';
    await Directory(dirPath).create(recursive: true);
    final String fileImagePath = '$dirPath/${timestamp()}.jpeg';
    if (cameraController.value.isRecordingVideo) {
      return null;
    }

    try {
       _photoPath=fileImagePath;
      await cameraController.takePicture(fileImagePath);
    } on CameraException catch (e) {
         logError(e.code, e.description);
      return null;
    }
    return _photoPath;
  }

  Future<void> stopVideoRecording() async {
    if (!cameraController.value.isRecordingVideo) {
     return null;
    }
    try {
      await cameraController.stopVideoRecording();
    } on CameraException catch (e) {
      return null;
    }
  }

 List<CameraDescription> cameras = [];
 Future<void> initCameras() async {
    try {
      WidgetsFlutterBinding.ensureInitialized();
      cameras = await availableCameras();
    } on CameraException catch (e) {
       logError(e.code, e.description);
    }
  }


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  
  //初始化摄像头 _camera=0 默认后置摄像头
  _initCamera([int _camera=0]){
      initCameras().then((a) => {
          cameraController =CameraController(cameras[_camera], ResolutionPreset.medium),
              cameraController.initialize().then((_) {
                if (!mounted) {
                  return;
                }
               setState(() {});
          })
        });
      _initPlatformState();
  }
}


 
